package concurrent;

import java.util.concurrent.*;

/**
 * User: Administrator
 * Date: 2021/1/29
 * Time: 16:16
 * Description:
 */
public class FutureDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Future<String> future = executorService.submit(() -> {
            try {
                Thread.sleep(5);
                System.out.println("task执行结束");
            } catch (InterruptedException e) {
                System.out.println("捕获到中断异常");
            }
            return "over";
        });
        System.out.println("main线程做其他事情");
        //取消任务 参数为是否可中断线程
        // false 线程被取消 但是不会中断 正常执行结束
        // true 线程被取消 并会中断
        future.cancel(true);
        boolean cancelled = future.isCancelled();
        System.out.println("task是否被取消： " + cancelled);
        try {
            System.out.println("task执行结果：" + future.get());
        } catch (InterruptedException | ExecutionException | CancellationException e) {
            e.printStackTrace();
        }
        System.out.println("结束");

        //关闭线程池
        /*executorService.shutdown();
        try {
            if (!executorService.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
                executorService.shutdownNow();
                if (!executorService.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
                    System.out.println("线程池关闭失败");
                }
            } else {
                System.out.println("线程池关闭成功");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }
}
